package botcraft.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Receiver implements Runnable {
	private static final Logger logger = Logger.getLogger(Receiver.class.getName());
	
	private final Worker worker;
	private final BlockingQueue<String> inputQueue;
	private final BufferedReader input;
	
	public Receiver(final Worker worker, final BlockingQueue<String> inputQueue, final BufferedReader input) {
		this.worker = worker;
		this.inputQueue = inputQueue;
		this.input = input;
	}
	
	@Override
	public void run() {
		while (!Thread.interrupted()) {
			try {
				final String command = input.readLine();
				if (command == null)
					Thread.currentThread().getThreadGroup().interrupt();
				else
					inputQueue.put(command);
			} catch (InterruptedException e) {
				return;
			} catch (IOException e) {
				logger.log(Level.WARNING, "Error receiving command from " + worker, e);
				Thread.currentThread().getThreadGroup().interrupt();
			}
		}
	}
}
